package org.youyun56.gpsserver.apache.tomcat;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;

public class HttpResponse {
    private HttpExchange exchange;
    private final static Logger logger = Logger.getLogger(HttpRequest.class);
    private static final String CACHE_CONTROL = "Cache-Control";
    private static final String PRAGMA = "Pragma";
    private static final int HTTP200 = 200;
    private final static Logger log = Logger.getLogger(HttpResponse.class);

    public HttpResponse(HttpExchange exchange) {
        // TODO Auto-generated constructor stub
        this.exchange = exchange;
        Headers headers = exchange.getResponseHeaders();
        List<String> noStore = new ArrayList<String>();
        noStore.add("no-store");
        List<String> noCache = new ArrayList<String>();
        noCache.add("no-cache");
        headers.put(CACHE_CONTROL, noStore);
        headers.put(PRAGMA, noCache);

    }

    public void write(Object obj) {
        OutputStream os = exchange.getResponseBody();
        try {
            if (obj == null) {
                String output = "not output";
                exchange.sendResponseHeaders(HTTP200, output.length());
                os.write(output.getBytes());
                os.close();
                return;
            }
            HttpRequest request = new HttpRequest(exchange);
            String str = new StringBuilder(request.getParameter("jsoncallback")).append("(").append(obj).append(")")
                    .toString();
            logger.info(String.format("Length : %d, %s", str.length(), str));
            byte[] buf = str.getBytes("utf-8");
            Headers headers = exchange.getResponseHeaders();
            headers.set("Content-Type", "text/plain");
            exchange.sendResponseHeaders(HTTP200, buf.length);
            os.write(buf);
            os.close();
            exchange.close();
        } catch (Exception e) {
            // TODO: handle exception
            log.error("response write out exception", e);
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                // e.printStackTrace();
            }
        }

    }

}
